com.mahees.jobTracker.views.JobPageView = com.mahees.backbone.View.BasicView.extend({

	tagName : 'tr',

	templateIdentifier : '#item-admin-template',

	events : {
		'click .deleteJobSite' : 'destroy',
		'click .checkUpdate' : 'checkUpdate',
		'click .saveJobSite' : 'saveJobSite',
		'change input' : 'updateModel'
	},

	customInitialize : function() {

	},

	saveJobSite : function(e) {
		e.preventDefault();
		// TODO: set calls validate right, but save doesnt
		this.model.isValid() && this.model.save();
		return false;
	},

	customRender : function() {
		$(this.el).removeClass('error');
	},

	checkUpdate : function(e) {
		e.preventDefault();
		this.model.checkChanges();
		return false;
	}

});

com.mahees.jobTracker.views.JobPagesCollectionView = com.mahees.backbone.View.BasicListView.extend({

	el : $('#jobPagesContainer'),

	events : {
		'click .addJobPage' : 'addItem',
		'click .updateAllJobSites' : 'updateAllJobSites',
		'click .logout' : 'logout'
	},
	
	refModelView : com.mahees.jobTracker.views.JobPageView,
	
	renderableArea : '#jobPages',

	customInitialize : function() {
		_.bindAll(this, 'updateAllJobSites', 'logout');
	},

	logout : function(e) {
		var self = this;

		e.preventDefault();
		$.get('../user/logout.json', function(resp) {
			window.authenticatedOnInit = false
			self.options.eventBus.trigger('navigate', 'login');
		});
		return false;
	},

	updateAllJobSites : function(e) {
		e.preventDefault();
		_.each(this.collection.models, function(model) {
			model.checkChanges()
		});
		return false;
	},

	customRender : function() {
		$(this.renderableArea, this.el).html($('#job-page-table-header-static-template').html());
	}

});

com.mahees.jobTracker.views.LoginRegisterView = Backbone.View.extend({

	el : $('#loginRegisterView'),

	events : {
		'click #signOnButton' : 'clickSignOnButton',
		'click #registerButton' : 'clickRegisterButton'
	},

	initialize : function() {

	},

	clickSignOnButton : function(e) {
		var self = this;
		// does post to resource to authenticate user credentials
		$.post('../user/login.json', {
			email : $('[name=email]', this.el).val()
		}, function(res) {
			window.authenticatedOnInit = true
			self.clearForm();
			self.options.eventBus.trigger('navigate', '');
		}).error(function(res) {
			var parsedRes = JSON.parse(res.responseText);

			var errorNode = self.generateErrorNode(parsedRes)

			$('#signOnMessage', self.el).html(errorNode)
		});
	},

	generateErrorNode : function(errorJson) {
		var errorsContainer = $(document.createElement('ul'));

		(!errorJson.errorMessage) || errorsContainer.append('<li>' + errorJson.errorMessage + '</li>');

		_.each(errorJson.fieldErrors, function(err) {
			$('[name=' + err.field + ']', self.el).addClass('error');

			var html = _.template($('#error-item-template').html(), err);
			errorsContainer.append(html);
		});

		return errorsContainer;
	},

	clickRegisterButton : function(e) {
		// register user
		var self = this;

		$.post('../user/register.json', {
			email : $('[name=email]', this.el).val()
		}, function(res) {
			var text = 'Registered successfully, try signing on with ' + res.email
			$('#signOnMessage', self.el).html(text)
		}).error(function(res) {
			var parsedRes = JSON.parse(res.responseText);

			var errorNode = self.generateErrorNode(parsedRes)

			$('#signOnMessage', self.el).html(errorNode)
		});
	},

	clearForm : function() {
		$('input[type=text]', this.el).val('').removeClass('error')
		$('#signOnMessage', this.el).html('')
	}
});

com.mahees.jobTracker.ApplicationRouter = Backbone.Router.extend({
	routes : {
		'' : 'index',
		'login' : 'login'
	},

	initialize : function() {
		_.bindAll(this, 'login', 'index');

		this.eventBus = new com.mahees.jobTracker.EventBus();
		this.eventBus.bind('navigate', function(url) {
			this.navigate(url, true)
		}, this);

		this.jobPagesCollection = new com.mahees.jobTracker.collections.JobPages;

		this.jobPagesCollectionView = new com.mahees.jobTracker.views.JobPagesCollectionView({
			collection : this.jobPagesCollection,
			eventBus : this.eventBus
		});

		this.loginRegisterView = new com.mahees.jobTracker.views.LoginRegisterView({
			eventBus : this.eventBus
		});
	},

	populateLocalStorageFromServer : function(collection) {
		$.getJSON('../rest/jobSite', function(data) {
			_.each(data, function(jobSite) {
				var foundSite = _.find(collection.models, function(model) {
					return model.get('pageUrl') == jobSite.pageUrl;
				});
				if (!foundSite) {
					var jobPage = new com.mahees.jobTracker.models.JobPage(jobSite);
					collection.create(jobPage);
				}
			});
		});
	},

	index : function() {
		if (!window.authenticatedOnInit) {
			this.navigate('login', true);
			return;
		}

		$('#loginRegisterView').hide();
		$('#jobPagesContainer').show();

		// this.populateLocalStorageFromServer(this.jobPagesCollection);

		this.jobPagesCollection.fetch();
	},

	login : function() {
		$('#loginRegisterView').show();
		$('#jobPagesContainer').hide();
	}
});